import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';
import { Message } from '@teamix/ui';
import { getOrgCrypto } from 'api';
import intl from '../../../../../../../../../locale';

const ns = NameSpace('crypto');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');

const { organization } = window.FORCE;

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

/**
 * 获取信息
 * noKeysReq 不请求keys
 * noLoading 无loading
 */
export function getCryptoInfo(noLoading = false, noKeysReq = false) {
  return (dispatch) => {
    if (!noLoading) {
      dispatch(
        updateData({
          isLoading: true,
        }),
      );
    }

    getOrgCrypto()
      .then((result) => {
        const cryptoInfo = result;
        dispatch(
          updateData({
            cryptoInfo,
            isLoading: false,
            isLoadingKeys: !noKeysReq,
          }),
        );

        // 查询keys列表以及设置库数据
        if (!noKeysReq) {
          dispatch(getKmsKeys());
        }
      })
      .catch((err) => {
        console.error(err);
        dispatch(
          updateData({
            isLoading: false,
          }),
        );
      });
  };
}

/**
 * 授权
 * @param {*} role
 */
export function cryptoAuthorize(role) {
  return (dispatch) => {
    dispatch(
      updateData({
        isAuthorizing: true,
      }),
    );

    exceed
      .fetch({
        api: 'org.cryptos.authorize',
        params: {
          org_id: organization.id,
        },

        data: {
          role,
        },
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.crypto.actions.ServiceAuthorizationCreated',
            defaultMessage: '服务授权创建成功',
          }),
        });
        dispatch(
          updateData({
            isAuthorizing: false,
          }),
        );

        dispatch(getCryptoInfo());
      })
      .fail((err) => {
        console.error(err);
        dispatch(
          updateData({
            isAuthorizing: false,
          }),
        );
      });
  };
}

const exceed2Promise = ({ api = '', params = {}, data = {} }) => {
  return new Promise((resolve, reject) => {
    exceed
      .fetch({
        api,
        params,
        data,
      })
      .then((result) => {
        resolve(result);
      })
      .fail((err) => {
        reject(err);
      });
  });
};

/**
 * 解除授权前校验，校验通过后，才真正解绑
 * @param {*} service_authorization_id
 */
export function removeBackupAuth(service_authorization_id) {
  return (dispatch) => {
    updateData({
      isRemovingAuth: true,
    })(dispatch);
    const verifyPromise = exceed2Promise({
      api: 'org.cryptos.removeAuthVerify',
      params: {
        org_id: organization.id,
      },

      data: {
        service_authorization_id,
      },
    });

    verifyPromise
      .then(() => {
        return exceed2Promise({
          api: 'org.cryptos.removeAuth',
          params: {
            org_id: organization.id,
          },

          data: {
            service_authorization_id,
          },
        });
      })
      .then(() => {
        dispatch(
          updateData({
            isRemovingAuth: false,
          }),
        );

        dispatch(getCryptoInfo());
      })
      .catch(() => {
        updateData({
          isRemovingAuth: false,
        })(dispatch);
      });
  };
}

/**
 * 获取KMS keys
 */
export function getKmsKeys() {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'org.cryptos.list',
        params: {
          org_id: organization.id,
        },

        data: {
          page: 1,
          per_page: 20,
        },
      })
      .then((result) => {
        result.shift(1);
        // 当前key只有一个
        const needRetryAuth = result.some((key) => !key.cmk);
        dispatch(
          updateData({
            keys: result,
            isLoadingKeys: false,
            needRetryAuth,
          }),
        );
      })
      .fail((err) => {
        console.error(err);
        const needRetryAuth = err.status === 403;
        dispatch(
          updateData({
            isLoadingKeys: false,
            needRetryAuth,
          }),
        );
      });
  };
}

/**
 * 更新设置
 */
export function updateCryptoInfo(data) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'org.cryptos.crypto_settings.put',
        params: {
          org_id: organization.id,
        },

        data,
      })
      .then(() => {
        dispatch(getCryptoInfo(true, true));
      })
      .fail(() => {});
  };
}
